<?php
//访问URL
function getFunction($url) {
	$get_url = $url;
	$get_return = file_get_contents ( $get_url );
	$get_return = ( array ) json_decode ( $get_return );
	if (! isset ( $get_return )) {
		exit ( '获取失败404！' );
	} else { // echo $get_return['access_token'];
		return $get_return;
	}
}
// 获取返回xml消息处理
function getPostData() {
	$PostData = $GLOBALS ['HTTP_RAW_POST_DATA'];
	
	if (! $PostData) {
        //echo_server_log ( "wrong input! PostData is NULL" );
		echo "wrong input!";
		exit ( 0 );
	} else {
		$xmlObj = simplexml_load_string ( $PostData, 'SimpleXMLElement', LIBXML_NOCDATA );
		if (! $xmlObj) {
			echo_server_log ( "wrong input! xmlObj is NULL\n" );
			echo "wrong input!";
			exit ( 0 );
		} else {
// 			$data['fromUserName'] = $xmlObj->FromUserName;
// 			$data['toUserName'] = $xmlObj->ToUserName;
// 			$data['msgType'] = $xmlObj->MsgType;
// 			$data['event'] = $xmlObj->Event;
// 			$data['eventKey'] = $xmlObj->EventKey;
//             $data['content'] = $xmlObj->Content;
		$data = $xmlObj;
		}
	}
	
	return $data;
}
//发送消息 MessageType---text
function postMessage ($data){
	
	$retTmp = "<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[%s]]></MsgType>
			<Content><![CDATA[%s]]></Content>
			<FuncFlag>0</FuncFlag>
			</xml>";
	$resultStr = sprintf($retTmp, $data['fromUserName'], $data['toUserName'], time(),$data['msgType'], $data['content']);
	echo $resultStr;
}

//获取AccessToken
function getAccessToken (){
	
	$get_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.C ( 'appID' ).'&secret='.C('appSecret');
	$get_return = file_get_contents ( $get_url );
	$get_return = ( array ) json_decode ( $get_return );
	if (! isset ( $get_return ['access_token'] )) {
		exit ( 'get access_token error' );
	}
	session('accessToken',$get_return ['access_token'],7200);
	return $get_return ['access_token'];
}

function UserInfo ($openID) {
	
	if (session('accessToken')==NULL){
		getAccessToken ();
	}
	$get_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.session('accessToken').'&openid='.$openID.'&lang=zh_CN';
	$get_return = file_get_contents ( $get_url );
	$get_return = ( array ) json_decode ( $get_return );
	return $get_return;
}
//网页 获取 用户信息
function getInfoPage ($code){
	//$code = $_GET ['code'];
	$get_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . C ( 'appID' ) . '&secret=' . C ( 'appSecret' ) . '&code=' . $code . '&grant_type=authorization_code';
	$get_return = getFunction ( $get_url );
	$openID = $get_return ['openid'];
	session( "openid", $openID, time () + 36000 );
	// echo $openID;
	$get_url2 = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $get_return ['access_token'] . '&openid=' . $get_return ['openid'] . '&lang=zh_CN';
	$get_return2 = getFunction ( $get_url2 );
	return $get_return2;
}